﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using FantastPlatform.Framework.IModel;
using FantastPlatform.Framework;
using FantastPlatform.Framework.IService;
using FantastPlatform.Framework.Model;
using FantastPlatform.Community.IService;
using FantastPlatform.Community.IMode;
using FantastPlatform.Community.Model;
using FantastPlatform.Community.Service;
using Yaxunsoft.CasesManagement;
using FantastPlatform.Framework.Core;

namespace FantastPlatform.Community.UI
{
    public partial class Default : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //清除页面缓存
            Page.Response.Buffer = false;
            Page.Response.Cache.SetNoStore();
            try
            {
                int criminalcount = 0;
                int securitycount = 0;
                if (LoginEmployee != null)
                {
                    if (LoginEmployee.User != null)
                    {
                        IList<IRole> roleList = LoginEmployee.User.Roles;
                        DateTime? startTime = getWeekStartTime();
                        this.loguser.Text = LoginEmployee.Name;
                        List<ResponsibilityArea> ResponsibilityAreaList = new List<ResponsibilityArea>();
                        IOrganization org = LoginEmployee.EmployeePosts[0].Post.Organization;
                        getResponsibilityArea(org, ResponsibilityAreaList);

                        List<string> roles = new List<string>();
                        foreach (IRole role in roleList)
                        {
                            roles.Add(role.Name);
                        }
                        if (roles.Contains("社区一级管理员") || roles.Contains("管理员"))
                        {
                            criminalcount = getCriminalCount(null, startTime, DateTime.Now);
                            securitycount = getSecurityCount(null, startTime, DateTime.Now);
                        }
                        else
                        {
                            foreach (ResponsibilityArea area in ResponsibilityAreaList)
                            {
                                criminalcount += getCriminalCount(area.Id, startTime, DateTime.Now);
                                securitycount += getSecurityCount(area.Id, startTime, DateTime.Now);
                            }
                        }
                    }
                    promptCount.InnerText = getPromptWorkLog(LoginEmployee.Id) + "条";
                    criminalCount.InnerText = criminalcount + "件";
                    securityCount.InnerText = securitycount + "件";
                    // businessCount.InnerText = "商" + getBusinessMindCount(LoginEmployee.Id) + "条";
                    houseHoldCount.InnerText = getHouseHoldMindCount(LoginEmployee.Id) + "条";
                }
                else
                {
                    Response.Redirect(AppUrl + "/SSLLogin.aspx", true);
                }
            }
            catch (Exception ex)
            {
                //Response.Redirect(AppUrl + "/Error.aspx", true);
            }
        }

        private void getResponsibilityArea(IOrganization org, List<ResponsibilityArea> areaList)
        {
            if (org.Children.Count == 0)
            {
                List<ResponsibilityArea> area = ResponsibilityAreaManager.LoadList(org.Name);
                if (area.Count > 0)
                    areaList.Add(area[0]);
            }
            else
            {
                foreach (IOrganization area in org.Children)
                {
                    getResponsibilityArea(area, areaList);
                }
            }
        }


        private string getPromptWorkLog(int policeId)
        {
            IWorkLogService workLogService = ServiceFactory.CreateService<IWorkLogService>();
            ConditionGroup group = new ConditionGroup();
            Condition enableCondition = new Condition() { Type = typeof(bool).FullName, Field = "Enable", Value1 = true };
            Condition condition1 = new Condition() { Type = typeof(bool).FullName, Field = "IsPrompt", Value1 = true, Relation = Relations.And };
            Condition condition2 = new Condition() { Type = typeof(int).FullName, Field = "PoliceMan.Id", Value1 = LoginEmployee.Id, Relation = Relations.And };
            group.Conditions.Add(enableCondition);
            group.Conditions.Add(condition1);
            group.Conditions.Add(condition2);
            int totalcount = 0;
            IList<IWorkLog> workList = workLogService.Search(group, null, int.MaxValue, 1, out totalcount);
            IList<IWorkLog> workPrompy = (from worklog in workList
                                          where worklog.PromptTime > DateTime.Now
                                          select worklog).ToList();
            changePromptTime(workList);
            return workPrompy.Count.ToString();
        }

        //修改已过期的提示状态
        private void changePromptTime(IList<IWorkLog> list)
        {
            try
            {
                IWorkLogService wlService = ServiceFactory.CreateService<IWorkLogService>();
                for (int i = 0; i < list.Count; i++)
                {
                    if (list[i].PromptTime < DateTime.Now)
                    {
                        list[i].IsPrompt = false;
                        wlService.Update(list[i]);
                    }
                }
            }
            catch (Exception e)
            {
            }
        }
        private int getBusinessMindCount(int policeManId)
        {
            IBusinessService businessService = ServiceFactory.CreateService<IBusinessService>();
            ConditionGroup group = new ConditionGroup();

            int totalCount = 0;
            group.Conditions.Add(new Condition() { Field = "Enable", Type = typeof(bool).FullName, Value1 = true });
            if (policeManId != 0)
            {
                group.Conditions.Add(new Condition() { Field = "PoliceMan.Id", Type = typeof(int).FullName, Value1 = policeManId });
            }
            group.Conditions.Add(new Condition() { Field = "Deadline", Type = typeof(DateTime).FullName, Value1 = DateTime.Now.AddDays(7), Comparison = Comparisons.Lt });
            businessService.Search(group, null, int.MaxValue, 1, out totalCount);
            return totalCount;
        }
        private int getHouseHoldMindCount(int policeManId)
        {
            IHouseHoldService houseHoldService = ServiceFactory.CreateService<IHouseHoldService>();
            ConditionGroup group = new ConditionGroup();
            int totalCount = 0;
            if (policeManId != 0)
            {

                group.Conditions.Add(new Condition() { Field = "Enable", Type = typeof(bool).FullName, Value1 = true });

                group.Conditions.Add(new Condition() { Field = "HouseDistrict.PoliceMan.Id", Type = typeof(int).FullName, Value1 = policeManId, Relation = Relations.And });

                group.Conditions.Add(new Condition() { Field = "Deadline", Type = typeof(DateTime).FullName, Value1 = DateTime.Now.AddDays(7), Comparison = Comparisons.Lt, Relation = Relations.And });

                IList<IHouseHold> list = houseHoldService.Search(group, null, int.MaxValue, 1, out totalCount);
                totalCount = (from l in list
                              where (from o in l.Purposes
                                     where o.Name == "出租"
                                     select o).Count() > 0
                              select l).Count();
            }
            return totalCount;
        }
        private int getCriminalCount(int? responsibilityAreaId, DateTime? startTime, DateTime? endTime)
        {
            CaseMainLineCondition condition = new CaseMainLineCondition();
            condition.ResponsibilityAreaId = responsibilityAreaId;
            condition.CaseCategoryId = 2;
            int totalCount = 0;
            List<CaseMainLine> list = CaseMainLineManager.LoadList(condition, 1, int.MaxValue, out totalCount);
            List<CaseMainLine> caseList = (from l in list
                                           where l.CaseHappendTimeLower > startTime && l.CaseHappendTimeLower <= endTime
                                           select l).ToList();
            return caseList.Count;
        }

        private int getSecurityCount(int? responsibilityAreaId, DateTime? startTime, DateTime? endTime)
        {
            CaseMainLineCondition condition = new CaseMainLineCondition();
            condition.ResponsibilityAreaId = responsibilityAreaId;
            condition.CaseCategoryId = 4;
            int totalCount = 0;
            List<CaseMainLine> list = CaseMainLineManager.LoadList(condition, 1, int.MaxValue, out totalCount);
            List<CaseMainLine> caseList = (from l in list
                                           where l.CaseHappendTimeLower > startTime && l.CaseHappendTimeLower <= endTime
                                           select l).ToList();
            return caseList.Count;
        }

        private DateTime? getWeekStartTime()
        {
            DateTime now = DateTime.Now;
            DayOfWeek weekDay = now.DayOfWeek;
            DateTime startTime = now.AddDays(-Convert.ToInt32(weekDay) + 1).Date;
            if (weekDay == 0)
                startTime = now.AddDays(-7 + 1).Date;

            return startTime;
        }
        public  bool GetAdminIII()
        {
            return true;
        }
        public  bool GetAdminII()
        {
            if (LoginEmployee != null)
            {
                if (LoginEmployee.User != null)
                {
                    IList<IRole> roleList = LoginEmployee.User.Roles;
                    List<string> roles = new List<string>();
                    foreach (IRole role in roleList)
                    {
                        roles.Add(role.Name);
                    }
                    if (roles.Contains("社区二级管理员"))
                    {
                        return true;
                    }
                }
            }
            return false;
        }
        public  bool GetAdminI()
        {

            if (LoginEmployee != null)
            {
                if (LoginEmployee.User != null)
                {
                    IList<IRole> roleList = LoginEmployee.User.Roles;
                    List<string> roles = new List<string>();
                    foreach (IRole role in roleList)
                    {
                        roles.Add(role.Name);
                    }
                    if (roles.Contains("社区一级管理员") || roles.Contains("管理员"))
                    {
                        return true;
                    }
                }
            }
            return false;
        }
    }
}
